package com.water.app;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;

@Component
public class QiniuUtil {
    private static final String accessKey="iuR8oA0AboCz3sIn7vQZdzr5GstYPLwSLjOtK3HC";
    private static final String secretKey="Q9Wsa-2JS29vdZp8EsEAERzpUwsGxtzlRc72mSJa";
    private static final String bucketName="waterlili";
    private static final String domain="t4ubtqmiq.hn-bkt.clouddn.com";

    /**
     * 上传图片到七牛云
     * @param file 前端文件
     * @param folder 存储文件夹（如“user-avatar/”）
     * @return 图片访问URL
     */
    public String uploadImage(MultipartFile file, String folder,String last) throws IOException {
        // 配置存储区域（华南对应Region.huanan()）
        Configuration cfg = new Configuration(Region.huanan());
        UploadManager uploadManager = new UploadManager(cfg);

        // 生成上传凭证
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucketName);

        try {
            // 处理文件名（UUID+原后缀，避免重复）
            // 1. 校验文件是否为空
            if (file.isEmpty()) {
                throw new RuntimeException("上传的图片文件不能为空！");
            }

            // 2. 获取文件名，校验是否有效
            String fileName = file.getOriginalFilename();
            if (fileName == null || fileName.trim().isEmpty()) {
                throw new RuntimeException("图片文件名无效！");
            }

            // 3. 截取后缀名（关键：判断是否包含 "."）
            int dotIndex = fileName.lastIndexOf(".");
            String suffix=null;
            if (dotIndex == -1) {
                // 无后缀名，抛出异常或默认用 .jpg
//                throw new RuntimeException("图片文件必须有后缀名（如 .jpg、.png）！");
                // 或：String suffix = ".jpg";（根据业务决定）
                suffix=".jpg";
            }
            // 确保起始索引 >=0，结束索引 <= 文件名长度
            if(suffix==null||suffix.isEmpty()) {
                suffix = fileName.substring(dotIndex); // 此时 dotIndex >=0，不会报错
            }
            fileName = folder + UUID.randomUUID()+ "/"+ last + suffix;

            // 上传文件
            Response response = uploadManager.put(file.getBytes(), fileName, upToken);
            if (!response.isOK()) {
                throw new RuntimeException("七牛云上传失败：" + response.bodyString());
            }

            // 拼接访问URL
            return "http://"+domain + "/" + fileName;
        } catch (QiniuException e) {
            throw new RuntimeException("七牛云上传异常：" + e.getMessage());
        }
    }
}